from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import ModelViewSet
import datetime, random, json, pymysql
from django.conf import settings
from random import randint, shuffle
from django.db.models import Q, Count, F, Sum

from merchants.serializers_lucky import *
from merchants.utils import get_wyf_order, get_wyf_order_settle
from equity_mall.utils.pages import MyPage
from customers.utils import AlipayOpen
from equity_mall.utils.utils import random_str, mmpaymkttransfers
from businesses.models import ScoutTheStoreLeaderboardRewards
from equity_mall.utils.utils import get_sign
from merchants.serializers import MerchantEightEightDrawListModelSerializer
from customers.utils import AlipayOpen as C_AlipayOpen


class LuckyBagActivityModelViewSet(ModelViewSet):

    def luckybagactivity(self, request):
        user = self.request.iser
        luckybagactivity = LuckyBagActivity.objects.get(id=1)
        data = {}
        data['activity_time'] = ''
        data['activity_set'] = []
        data['description'] = ''
        data['explain'] = ''
        if luckybagactivity.available_end_time >= datetime.datetime.now():
            if user.id in [2]:
                data = LuckyBagActivityModelSerializer1(luckybagactivity).data
            else:
                data = LuckyBagActivityModelSerializer(luckybagactivity).data
        return Response(data, status=status.HTTP_200_OK)


class LuckyBagChildActivityModelViewSet(ModelViewSet):

    def get_queryset(self):
        today = datetime.datetime.now()
        queryset = LuckyBagChildActivity.objects.filter(parent__available_end_time__gte=today)
        return queryset

    def luckybagactivitychild(self, request):
        user = self.request.iser
        business_no = self.request.data.get('business_no', None)
        activity_id = self.request.data.get('activity_id', None)
        if not business_no:
            return Response({'error': '请上传商户号'}, status=status.HTTP_400_BAD_REQUEST)
        business_no = str(business_no)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no, merchantuser_id=user.id)
        except:
            return Response({'error': '无效商户号'}, status=status.HTTP_400_BAD_REQUEST)
        today = datetime.datetime.now()
        yesterday = today - datetime.timedelta(1)
        try:
            instance = self.get_queryset().get(id=activity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_200_OK)
        data = {}
        data['status'] = 1
        data['limit_time_description'] = instance.limit_time_description
        data['limit_day_description'] = instance.limit_day_description
        data['description'] = instance.description
        data['count'] = 0
        if instance.activity_type == 1:
            luckybagmerchantorder = LuckyBagMerchantOrder.objects.filter(trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"), business_no=business_no, activity_type=1).first()
            if not luckybagmerchantorder:
                result = get_wyf_order(business_no, yesterday.strftime("%Y-%m-%d 00:00:00"),yesterday.strftime("%Y-%m-%d 23:59:59"))
                luckybagmerchantorder_data = {}
                luckybagmerchantorder_data['trade_time'] = yesterday.strftime("%Y-%m-%d 00:00:00")
                luckybagmerchantorder_data['business_no'] = business_no
                luckybagmerchantorder_data['activity_type'] = 1
                if result:
                    luckybagmerchantorder_data['is_standard'] = 1
                    luckybagmerchantorder_data['trade_no'] = result['channelTradeNo']
                    luckybagmerchantorder_data['trade_amount'] = result['totalNormal']
                else:
                    luckybagmerchantorder_data['is_standard'] = 0
                luckybagmerchantorder, create = LuckyBagMerchantOrder.objects.get_or_create(defaults=luckybagmerchantorder_data, business_no=business_no,trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"),activity_type=1)
            data['lists'] = [{"status": 0}, {"status": 0}, {"status": 0}]
            if luckybagmerchantorder.is_standard == 0:
                data['status'] = 3
            else:
                lucky_data = LuckyBagChildActivityData.objects.filter(open_time=today.strftime("%Y-%m-%d 00:00:00"), business_no=business_no, luckybagchildactivity_id=instance.id).first()
                if lucky_data:
                    data['lists'][lucky_data.index] = {"lucky_bag": int(lucky_data.lucky_bag), "status": 1}
                    data['status'] = 2
                else:
                    check_rule = LuckyBagChildActivityRule.objects.filter(validity_time=today.strftime('%Y-%m-%d 00:00:00'), is_occupy=0, activity_type=1)
                    if not check_rule:
                        data['status'] = 0
                    else:
                        data['count'] = 1
                        data['status'] = 1
        elif instance.activity_type == 4:
            data['lists'] = [{"status": 0}, {"status": 0}, {"status": 0}]
            check_rule = LuckyBagChildActivityRule.objects.filter(is_occupy=2, activity_type=4, business_no=business_no)
            if not check_rule:
                lucky_data = LuckyBagChildActivityData.objects.filter(open_time=today.strftime("%Y-%m-%d 00:00:00"), business_no=business_no, luckybagchildactivity_id=instance.id).first()
                if lucky_data:
                    data['lists'][lucky_data.index] = {"lucky_bag": int(lucky_data.lucky_bag), "status": 1}
                    data['status'] = 2
                else:
                    luckybagmerchantorder = LuckyBagMerchantOrder.objects.filter(trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"), business_no=business_no, activity_type=4).first()
                    if not luckybagmerchantorder:
                        result = get_wyf_order_settle(business_no, yesterday.strftime("%Y-%m-%d 00:00:00"),yesterday.strftime("%Y-%m-%d 23:59:59"))
                        luckybagmerchantorder_data = {}
                        luckybagmerchantorder_data['trade_time'] = yesterday.strftime("%Y-%m-%d 00:00:00")
                        luckybagmerchantorder_data['business_no'] = business_no
                        luckybagmerchantorder_data['activity_type'] = 4
                        if Decimal(str(result)) >= Decimal('88'):
                            luckybagmerchantorder_data['is_standard'] = 1
                            # luckybagmerchantorder_data['trade_no'] = result['channelTradeNo']
                            luckybagmerchantorder_data['trade_amount'] = result
                        else:
                            luckybagmerchantorder_data['trade_amount'] = result
                            luckybagmerchantorder_data['is_standard'] = 0
                        luckybagmerchantorder, create = LuckyBagMerchantOrder.objects.get_or_create(defaults=luckybagmerchantorder_data, business_no=business_no,trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"),activity_type=4)
                    if luckybagmerchantorder.is_standard == 0:
                        data['status'] = 3
                    else:
                        check_rule = LuckyBagChildActivityRule.objects.filter(validity_time=today.strftime('%Y-%m-%d 00:00:00'), is_occupy=0, activity_type=4)
                        if not check_rule:
                            data['status'] = 0
                        else:
                            data['count'] = 1
                            data['status'] = 1
            else:
                lucky_data = LuckyBagChildActivityData.objects.filter(open_time=today.strftime("%Y-%m-%d 00:00:00"), business_no=business_no, luckybagchildactivity_id=instance.id).first()
                if lucky_data:
                    data['lists'][lucky_data.index] = {"lucky_bag": int(lucky_data.lucky_bag), "status": 1}
                    data['status'] = 2
                else:
                    data['count'] = 1
                    data['status'] = 1
        elif instance.activity_type == 2:
            lucky_data = LuckyBagChildActivityData.objects.filter(expired_time__gte=today, business_no=business_no, luckybagchildactivity_id=instance.id, lucky_status=0)
            if not lucky_data:
                data['status'] = 3
                data['scrollText1'] = ['-1']
                data['scrollText2'] = ['-1']
                data['scrollText3'] = ['-1']
            else:
                lucky_bag = lucky_data.first().lucky_bag
                if lucky_bag >= Decimal('100'):
                    lucky_bag = str(lucky_bag)
                    lucky_bag_0 = int(lucky_bag[0])
                    lucky_bag_1 = int(lucky_bag[1])
                    lucky_bag_2 = int(lucky_bag[2])
                else:
                    lucky_bag = str(lucky_bag)
                    lucky_bag_0 = 0
                    lucky_bag_1 = int(lucky_bag[0])
                    lucky_bag_2 = int(lucky_bag[1])
                if lucky_data.first().lucky_status == 0:
                    data['status'] = 1
                    data['count'] = lucky_data.count()
                    scrollText1 = [random.randrange(0, 10) for _ in range(20)]
                    scrollText2 = [random.randrange(0, 10) for _ in range(20)]
                    scrollText3 = [random.randrange(0, 10) for _ in range(20)]
                    scrollText1[0] = '-1'
                    scrollText2[0] = '-1'
                    scrollText3[0] = '-1'
                else:
                    data['status'] = 2
                    scrollText1 = []
                    scrollText2 = []
                    scrollText3 = []
                scrollText1.append(lucky_bag_0)
                scrollText2.append(lucky_bag_1)
                scrollText3.append(lucky_bag_2)
                data['scrollText1'] = scrollText1
                data['scrollText2'] = scrollText2
                data['scrollText3'] = scrollText3
        else:
            lucky_data = LuckyBagChildActivityData.objects.filter(expired_time__gte=today, business_no=business_no, luckybagchildactivity_id=instance.id).first()
            if not lucky_data:
                data['status'] = 3
                data['lucky_bag'] = ''
            else:
                if lucky_data.lucky_status == 0:
                    data['status'] = 1
                    data['count'] = 1
                    data['lucky_bag'] = ''
                else:
                    data['status'] = 2
                    data['lucky_bag'] = int(lucky_data.lucky_bag)
        return Response(data, status=status.HTTP_200_OK)

    def open_luckybag(self, request, *args, **kwargs):
        user = self.request.iser
        business_no = self.request.data.get('business_no', None)
        activity_id = self.request.data.get('activity_id', None)
        index = self.request.data.get('index', None)
        if not business_no:
            return Response({'error': '请上传商户号'}, status=status.HTTP_400_BAD_REQUEST)
        business_no = str(business_no)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no, merchantuser_id=user.id)
        except:
            return Response({'error': '无效商户号'}, status=status.HTTP_400_BAD_REQUEST)
        today = datetime.datetime.now()
        yesterday = today - datetime.timedelta(1)
        try:
            instance = self.get_queryset().get(id=activity_id)
        except:
            return Response({'error': '无效活动id'}, status=status.HTTP_200_OK)
        if instance.available_end_time <= today:
            return Response({'error': '活动已结束'}, status=status.HTTP_400_BAD_REQUEST)
        week = str(today.weekday())
        enable_time = today.strftime('1970-01-01 %H:%M:%S')
        alidiscountcoupondstributedlimit = LuckyBagChildActivityDistributedLimit.objects.filter(luckybagchildactivity_id=instance.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
        if not alidiscountcoupondstributedlimit:
            return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.activity_type == 1:
            # if not index:
            #     return Response({'error': '请选择抽奖福袋'}, status=status.HTTP_400_BAD_REQUEST)
            if index not in [0, 1, 2]:
                return Response({'error': '选择的福袋下标有误'}, status=status.HTTP_400_BAD_REQUEST)
            lucky_data = LuckyBagChildActivityData.objects.filter(open_time=today.strftime("%Y-%m-%d 00:00:00"), business_no=business_no, luckybagchildactivity_id=instance.id).first()
            if lucky_data:
                return Response({'error': '今日已领取,不可重复领取'}, status=status.HTTP_400_BAD_REQUEST)
            luckybagmerchantorder = LuckyBagMerchantOrder.objects.filter(trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"), business_no=business_no, activity_type=1).first()
            if not luckybagmerchantorder:
                result = get_wyf_order(business_no, yesterday.strftime("%Y-%m-%d 00:00:00"), yesterday.strftime("%Y-%m-%d 23:59:59"))
                luckybagmerchantorder_data = {}
                luckybagmerchantorder_data['trade_time'] = yesterday.strftime("%Y-%m-%d 00:00:00")
                luckybagmerchantorder_data['business_no'] = business_no
                luckybagmerchantorder_data['activity_type'] = 1
                if result:
                    luckybagmerchantorder_data['is_standard'] = 1
                    luckybagmerchantorder_data['trade_no'] = result['channelTradeNo']
                    luckybagmerchantorder_data['trade_amount'] = result['totalNormal']
                else:
                    luckybagmerchantorder_data['is_standard'] = 0
                luckybagmerchantorder, create = LuckyBagMerchantOrder.objects.get_or_create(defaults=luckybagmerchantorder_data, business_no=business_no, trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"), activity_type=1)
            # if business_no in ["6087887344", "6067103814", "6048505860", "6037619779"]:
            #     check_rule = LuckyBagChildActivityRule.objects.filter(validity_time=today.strftime('%Y-%m-%d 00:00:00'), is_occupy=0, id__in=[229069,229070,229071,229072,229073,229074,229075,229076,229077,229078])
            # else:
            check_rule = LuckyBagChildActivityRule.objects.filter(validity_time=today.strftime('%Y-%m-%d 00:00:00'), is_occupy=0, activity_type=1)
            if not check_rule:
                return Response({'error': '很遗憾,今日福袋已派完'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if luckybagmerchantorder.is_standard == 0:
                    return Response({'error': '商户未达标'}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    rule = check_rule[random.randint(0, len(check_rule)-1)]
                    rule.is_occupy = 1
                    rule.business_no = business_no
                    rule.save()
                    lucky_bag = rule.lucky_bag
                    defaults = {}
                    defaults['merchantuser_id'] = user.id
                    defaults['business_no'] = business_no
                    defaults['lucky_bag'] = lucky_bag
                    defaults['open_time'] = today.strftime('%Y-%m-%d 00:00:00')
                    defaults['received_time'] = today
                    defaults['index'] = index
                    defaults['luckybagchildactivity_id'] = instance.id
                    defaults['lucky_status'] = 2
                    defaults['level_id'] = merchant.level_id
                    luckybagchildactivitydata, create = LuckyBagChildActivityData.objects.get_or_create(defaults=defaults, luckybagchildactivity_id=instance.id, open_time=today.strftime('%Y-%m-%d 00:00:00'), business_no=business_no)
                    if create:
                        user_id = user.id
                        while True:
                            user = MerchantUser.objects.get(id=user_id)
                            origin_lucky_bag = user.lucky_bag
                            new_lucky_bag = origin_lucky_bag + lucky_bag
                            result = MerchantUser.objects.filter(id=user_id, lucky_bag=origin_lucky_bag).update(lucky_bag=new_lucky_bag)
                            if result == 0:
                                continue
                            break
                        LuckyBagRecord.objects.create(
                            merchantuser_id=user.id,
                            create_time=today,
                            operate_type=1,
                            activitydata_id=luckybagchildactivitydata.id,
                            lucky_bag=lucky_bag,
                            lucky_bag_balance=new_lucky_bag,
                        )
        elif instance.activity_type == 4:
            # if not index:
            #     return Response({'error': '请选择抽奖福袋'}, status=status.HTTP_400_BAD_REQUEST)
            if index not in [0, 1, 2]:
                return Response({'error': '选择的福袋下标有误'}, status=status.HTTP_400_BAD_REQUEST)
            lucky_data = LuckyBagChildActivityData.objects.filter(open_time=today.strftime("%Y-%m-%d 00:00:00"), business_no=business_no, luckybagchildactivity_id=instance.id).first()
            if lucky_data:
                return Response({'error': '今日已领取,不可重复领取'}, status=status.HTTP_400_BAD_REQUEST)
            check_rule = LuckyBagChildActivityRule.objects.filter(is_occupy=2, activity_type=4, business_no=business_no)
            if not check_rule:
                luckybagmerchantorder = LuckyBagMerchantOrder.objects.filter(trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"), business_no=business_no, activity_type=4).first()
                if not luckybagmerchantorder:
                    result = get_wyf_order_settle(business_no, yesterday.strftime("%Y-%m-%d 00:00:00"), yesterday.strftime("%Y-%m-%d 23:59:59"))
                    luckybagmerchantorder_data = {}
                    luckybagmerchantorder_data['trade_time'] = yesterday.strftime("%Y-%m-%d 00:00:00")
                    luckybagmerchantorder_data['business_no'] = business_no
                    luckybagmerchantorder_data['activity_type'] = 4
                    if Decimal(str(result)) >= Decimal('88'):
                        luckybagmerchantorder_data['is_standard'] = 1
                        # luckybagmerchantorder_data['trade_no'] = result['channelTradeNo']
                        luckybagmerchantorder_data['trade_amount'] = result
                    else:
                        luckybagmerchantorder_data['is_standard'] = 0
                        luckybagmerchantorder_data['trade_amount'] = result
                    luckybagmerchantorder, create = LuckyBagMerchantOrder.objects.get_or_create(defaults=luckybagmerchantorder_data, business_no=business_no, trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"), activity_type=4)
                check_rule = LuckyBagChildActivityRule.objects.filter(validity_time=today.strftime('%Y-%m-%d 00:00:00'), is_occupy=0, activity_type=4)
                if not check_rule:
                    return Response({'error': '很遗憾,今日福袋已派完'}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    if luckybagmerchantorder.is_standard == 0:
                        return Response({'error': '商户未达标'}, status=status.HTTP_400_BAD_REQUEST)
                    else:
                        rule = check_rule[random.randint(0, len(check_rule)-1)]
                        rule.is_occupy = 1
                        rule.business_no = business_no
                        rule.save()
                        lucky_bag = rule.lucky_bag
                        defaults = {}
                        defaults['merchantuser_id'] = user.id
                        defaults['business_no'] = business_no
                        defaults['lucky_bag'] = lucky_bag
                        defaults['open_time'] = today.strftime('%Y-%m-%d 00:00:00')
                        defaults['received_time'] = today
                        defaults['index'] = index
                        defaults['luckybagchildactivity_id'] = instance.id
                        defaults['lucky_status'] = 2
                        defaults['level_id'] = merchant.level_id
                        luckybagchildactivitydata, create = LuckyBagChildActivityData.objects.get_or_create(defaults=defaults, luckybagchildactivity_id=instance.id, open_time=today.strftime('%Y-%m-%d 00:00:00'), business_no=business_no)
                        if create:
                            user_id = user.id
                            while True:
                                user = MerchantUser.objects.get(id=user_id)
                                origin_lucky_bag = user.lucky_bag
                                new_lucky_bag = origin_lucky_bag + lucky_bag
                                result = MerchantUser.objects.filter(id=user_id, lucky_bag=origin_lucky_bag).update(lucky_bag=new_lucky_bag)
                                if result == 0:
                                    continue
                                break
                            LuckyBagRecord.objects.create(
                                merchantuser_id=user.id,
                                create_time=today,
                                operate_type=1,
                                activitydata_id=luckybagchildactivitydata.id,
                                lucky_bag=lucky_bag,
                                lucky_bag_balance=new_lucky_bag,
                            )
            else:
                rule = check_rule[random.randint(0, len(check_rule) - 1)]
                rule.is_occupy = 1
                rule.business_no = business_no
                rule.save()
                lucky_bag = rule.lucky_bag
                defaults = {}
                defaults['merchantuser_id'] = user.id
                defaults['business_no'] = business_no
                defaults['lucky_bag'] = lucky_bag
                defaults['open_time'] = today.strftime('%Y-%m-%d 00:00:00')
                defaults['received_time'] = today
                defaults['index'] = index
                defaults['luckybagchildactivity_id'] = instance.id
                defaults['lucky_status'] = 2
                defaults['level_id'] = merchant.level_id
                luckybagchildactivitydata, create = LuckyBagChildActivityData.objects.get_or_create(defaults=defaults, luckybagchildactivity_id=instance.id, open_time=today.strftime('%Y-%m-%d 00:00:00'), business_no=business_no)
                if create:
                    user_id = user.id
                    while True:
                        user = MerchantUser.objects.get(id=user_id)
                        origin_lucky_bag = user.lucky_bag
                        new_lucky_bag = origin_lucky_bag + lucky_bag
                        result = MerchantUser.objects.filter(id=user_id, lucky_bag=origin_lucky_bag).update(
                            lucky_bag=new_lucky_bag)
                        if result == 0:
                            continue
                        break
                    LuckyBagRecord.objects.create(
                        merchantuser_id=user.id,
                        create_time=today,
                        operate_type=1,
                        activitydata_id=luckybagchildactivitydata.id,
                        lucky_bag=lucky_bag,
                        lucky_bag_balance=new_lucky_bag,
                    )
        else:
            luckybagchildactivitydata = LuckyBagChildActivityData.objects.filter(expired_time__gte=today, business_no=business_no, luckybagchildactivity_id=instance.id, lucky_status=0).first()
            if not luckybagchildactivitydata:
                return Response({'error': '商户未达标'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if luckybagchildactivitydata.lucky_status != 0:
                    return Response({'error': '已经完成抽奖'}, status=status.HTTP_400_BAD_REQUEST)
                lucky_bag = luckybagchildactivitydata.lucky_bag
                luckybagchildactivitydata.lucky_status = 2
                luckybagchildactivitydata.open_time = today.strftime('%Y-%m-%d 00:00:00')
                luckybagchildactivitydata.received_time = today
                luckybagchildactivitydata.merchantuser_id = user.id
                luckybagchildactivitydata.save()
                user_id = user.id
                while True:
                    user = MerchantUser.objects.get(id=user_id)
                    origin_lucky_bag = user.lucky_bag
                    new_lucky_bag = origin_lucky_bag + lucky_bag
                    result = MerchantUser.objects.filter(id=user_id, lucky_bag=origin_lucky_bag).update(lucky_bag=new_lucky_bag)
                    if result == 0:
                        continue
                    break
                LuckyBagRecord.objects.create(
                    merchantuser_id=user.id,
                    create_time=today,
                    operate_type=1,
                    activitydata_id=luckybagchildactivitydata.id,
                    lucky_bag=lucky_bag,
                    lucky_bag_balance=new_lucky_bag,
                )
        return Response({'success': '抽奖成功', 'lucky_bag': int(lucky_bag)}, status=status.HTTP_200_OK)


class LuckyBagRecordModelViewSet(ModelViewSet):

    pagination_class = MyPage

    def get_queryset(self):
        user = self.request.iser
        queryset = LuckyBagRecord.objects.filter(merchantuser_id=user.id)
        return queryset.order_by('-id')

    def get_serializer_class(self):
        if self.action == 'list':
            return LuckyBagRecordListModelSerializer

    def luckybagclaimprize(self, request):
        user = self.request.iser
        if user.is_psbc_card != 1:
            return Response({'error': '请先做邮储卡绑定'}, status=status.HTTP_400_BAD_REQUEST)
        lucky_bag = self.request.data.get('lucky_bag', None)
        login_id = self.request.data.get('login_id', None)
        realname = self.request.data.get('realname', None)
        if not lucky_bag:
            return Response({'error': '请上传兑换福袋数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            lucky_bag = Decimal(int(lucky_bag))
        except:
            return Response({'error': '福袋数参数格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        if lucky_bag < Decimal('50'):
            return Response({'error': '兑换的福袋数须大于50'}, status=status.HTTP_400_BAD_REQUEST)
        if lucky_bag > user.lucky_bag:
            return Response({'error': '用户福袋不足'}, status=status.HTTP_400_BAD_REQUEST)
        cash_activity = CashActivity.objects.get(id=836)
        today = datetime.datetime.now()
        if cash_activity.available_end_time < today:
            return Response({'error': '兑奖活动已结束'}, status=status.HTTP_400_BAD_REQUEST)
        if lucky_bag > Decimal('2000'):
            if not all([login_id, realname]):
                return Response({'error': '超过2000福袋兑换,请使用支付宝兑换'}, status=status.HTTP_400_BAD_REQUEST)
        user_id = user.id
        while True:
            user = MerchantUser.objects.get(id=user_id)
            origin_lucky_bag = user.lucky_bag
            new_lucky_bag = origin_lucky_bag - lucky_bag
            result = MerchantUser.objects.filter(id=user_id, lucky_bag=origin_lucky_bag).update(lucky_bag=new_lucky_bag)
            if result == 0:
                continue
            break
        if lucky_bag > Decimal('2000'):
            alipay_obj = AlipayOpen()
            trans_amount = str(lucky_bag/10)
            order_title = cash_activity.name
            partner_trade_no = f'{today.strftime("%Y%m%d%H%M%S")}{"%06d" % random.randint(0,999999)}{"%07d" % user_id}'
            out_biz_no = partner_trade_no
            identity = login_id
            if cash_activity.ali_channel_id == 8:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88(identity, realname, out_biz_no, trans_amount, order_title))
            elif cash_activity.ali_channel_id == 11:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88_jizhangben(identity, realname, out_biz_no, trans_amount, order_title))
            else:
                result = json.loads(alipay_obj.transunitransfer_login_id(identity, realname, out_biz_no, trans_amount, order_title))
            activity_data = {}
            activity_data['amount'] = trans_amount
            activity_data['create_time'] = today
            activity_data['cash_activity_id'] = cash_activity.id
            activity_data['state'] = 1
            identify = random_str()
            nonce_str = random_str()
            activity_data['identify'] = identify
            activity_data['nonce_str'] = nonce_str
            activity_data['desc'] = cash_activity.name
            activity_data['partner_trade_no'] = partner_trade_no
            activity_data['merchantuser_id'] = user_id
            activity_data['channel_id'] = cash_activity.ali_channel_id
            activity_data['mobile'] = user.mobile
            activity_data['login_id'] = login_id
            activity_data['realname'] = realname
            if result['code'] != '10000':
                activity_data['state'] = 3
                activity_data['return_msg'] = result['sub_msg']
                activity_data['received_time'] = today
                activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                user_id = user.id
                while True:
                    user = MerchantUser.objects.get(id=user_id)
                    origin_lucky_bag = user.lucky_bag
                    new_lucky_bag = origin_lucky_bag + lucky_bag
                    result1 = MerchantUser.objects.filter(id=user_id, lucky_bag=origin_lucky_bag).update(lucky_bag=new_lucky_bag)
                    if result1 == 0:
                        continue
                    break
                return Response({'error': f'兑换失败,原因:{result["sub_msg"]}'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                activity_data['state'] = 2
                activity_data['payment_no'] = result['pay_fund_order_id']
                activity_data['received_time'] = result['trans_date']
                activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                LuckyBagRecord.objects.create(
                    merchantuser_id=user.id,
                    create_time=today,
                    operate_type=2,
                    cashactivitydata_id=activity_dat.id,
                    lucky_bag=lucky_bag,
                    lucky_bag_balance=new_lucky_bag,
                )
                conn = pymysql.connect(host=settings.DATABASES['open']['HOST'],
                                       port=settings.DATABASES['open']['PORT'],
                                       database=settings.DATABASES['open']['NAME'],
                                       user=settings.DATABASES['open']['USER'],
                                       password=settings.DATABASES['open']['PASSWORD'])
                cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
                try:
                    sql = f'''SELECT id FROM tb_m_merchant_user WHERE mobile="{user.mobile}";'''
                    cursor.execute(sql)
                    row = cursor.fetchone()
                    if row:
                        sql = f'''INSERT INTO tb_m_encourage_ali_account(account,`name`,merchant_user_id) SELECT "{login_id}","{realname}",{row['id']} WHERE NOT EXISTS (SELECT 1 FROM tb_m_encourage_ali_account WHERE account="{login_id}" AND `name`="{realname}" AND merchant_user_id={row['id']});'''
                        cursor.execute(sql)
                        conn.commit()
                except:
                    conn.rollback()
                finally:
                    cursor.close()
                    conn.close()
                return Response({"success": '兑换成功'}, status=status.HTTP_200_OK)
        else:
            appid = 'wxbf07fc5376ab43a2'
            openid = user.openid
            nonce_str = random_str()
            partner_trade_no = f'{today.strftime("%Y%m%d%H%M%S")}{"%06d" % random.randint(0,999999)}{"%07d" % user_id}'
            trans_amount = str(lucky_bag/10)
            params = {
                'mch_appid': appid,
                'mchid': '1486198522',  # 商户号
                'nonce_str': nonce_str,
                'partner_trade_no': partner_trade_no,
                'openid': openid,
                'check_name': 'NO_CHECK',
                'amount': int(Decimal(trans_amount) * 100),
                'desc': cash_activity.name
            }
            data_dict = mmpaymkttransfers(params)
            activity_data = {}
            activity_data['amount'] = trans_amount
            activity_data['create_time'] = today
            activity_data['cash_activity_id'] = cash_activity.id
            activity_data['state'] = 1
            identify = random_str()
            activity_data['identify'] = identify
            activity_data['nonce_str'] = nonce_str
            activity_data['desc'] = cash_activity.name
            activity_data['partner_trade_no'] = partner_trade_no
            activity_data['merchantuser_id'] = user_id
            activity_data['channel_id'] = cash_activity.wx_channel_id
            activity_data['openid'] = openid
            activity_data['appid'] = appid
            activity_data['mobile'] = user.mobile
            if data_dict['result_code'] == 'SUCCESS':
                activity_data['state'] = 2
                activity_data['payment_no'] = data_dict['payment_no']
                activity_data['received_time'] = data_dict['payment_time']
                activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                LuckyBagRecord.objects.create(
                    merchantuser_id=user.id,
                    create_time=today,
                    operate_type=2,
                    cashactivitydata_id=activity_dat.id,
                    lucky_bag=lucky_bag,
                    lucky_bag_balance=new_lucky_bag,
                )
                return Response({"success": '兑换成功'}, status=status.HTTP_200_OK)
            else:
                activity_data['state'] = 3
                activity_data['return_msg'] = data_dict['err_code_des']
                activity_data['received_time'] = today
                activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                while True:
                    user = MerchantUser.objects.get(id=user_id)
                    origin_lucky_bag = user.lucky_bag
                    new_lucky_bag = origin_lucky_bag + lucky_bag
                    result = MerchantUser.objects.filter(id=user_id, lucky_bag=origin_lucky_bag).update(lucky_bag=new_lucky_bag)
                    if result == 0:
                        continue
                    break
                return Response({'error': f'兑换失败,原因:{data_dict["err_code_des"]}'}, status=status.HTTP_400_BAD_REQUEST)


class ScoutTheStoreLeaderboardModelViewSet(ModelViewSet):

    serializer_class = ScoutTheStoreLeaderboardModelSerializer

    def get_queryset(self):
        queryset = ScoutTheStoreLeaderboard.objects.all().order_by('-likes')
        return queryset

    def list(self, request, *args, **kwargs):
        data = {}
        queryset = self.filter_queryset(self.get_queryset())
        update_time = queryset.first().update_time.strftime("%m月%d日%H:%M:%S")
        description1 = f'''排行榜每周一、周三、周五更新，排名统计截止至{update_time}'''
        description2 = '''活动时间：即日起至10月7日
活动对象：广东省微邮付商户
活动内容：活动期间，拍摄广东省微邮付商户探店视频，有机会上传至“粤小邮探店”微信视频号，参与探店视频评选，点赞量全省前三名可获ipad大奖！'''
        serializer = self.get_serializer(queryset, many=True)
        data['list'] = serializer.data
        data['description1'] = description1
        data['description2'] = description2
        data['update_time'] = update_time
        return Response(data, status=status.HTTP_200_OK)

    def reward_info(self, request):
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        if not business_no:
            return Response({'error': '请上传商户号'}, status=status.HTTP_400_BAD_REQUEST)
        reward_set = ScoutTheStoreLeaderboardRewards.objects.filter(business_no=business_no, mobile=user.mobile)
        if not reward_set:
            return Response({'error': '无效中奖商户'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        data['award_time'] = ''
        data['popularity'] = ''
        data['rank'] = ''
        data['description'] = '''1.活动须知：
(1)活动时间：10月10日-10月18日
(2)活动规则：活动期间，88商户节“热力探店·人气点赞”排行榜活动中，截止2024年10月7日23:59:59人气值排名前30名的微邮付商户可领取相应奖励，每个商户每个奖品仅可领取一次，逾期未领取视为放弃。
(3)排名查看：商户可前往“微邮惠商圈”小程序-点击首页顶部“广东省88商户节”广告-点击“热力探店·人气点赞”进入排行榜页面查看排名情况。
2.奖品内容：
(1)全省冠军商家：ipad 1台、2000元支付宝权益、价值1000元小邮美宿优惠券包
(2)全省亚军商家：ipad 1台、1000元支付宝权益、价值1000元小邮美宿优惠券包
(3)全省季军商家：ipad 1台、500元支付宝权益、价值300元小邮美宿优惠券
(4)全省第4~15名：388元支付宝权益、价值100元小邮美宿优惠券
(5)全省第16~30名：388元支付宝权益
3.奖品领取规则：
(1)实物礼品：获奖商户点击领取后，填写个人姓名、联系方式及门店地址，确认提交后不可修改，届时礼品将在15个工作日内由网点客户经理送货至商户门店。如收货信息有误，请联系相应客户经理进行备注修改。
(2)支付宝权益：获奖商户点击领取后，填写支付宝账户信息，确认无误后提交即可，权益将在1个工作日内发放至相关支付宝账户，商户可留意支付宝账户到账情况。奖励发放后无法撤销，提交前请注意核实支付宝信息是否有误。
(3)小邮美宿优惠券（包）：获奖商户点击领取后，券（包）直接到账商户手机号所绑定的小邮美宿平台账号，商户领取后，可点击页面上的“去使用”按钮，即可跳转至小邮美宿平台查看优惠券到账情况。优惠券的具体使用规则以小邮美宿平台展示为准。
'''
        lists = []
        for reward in reward_set:
            try:
                reward_lists = json.loads(reward.reward_lists)
            except:
                reward_lists = []
            if reward.reward_status == 1:
                reward_status_str = '立即领取'
            elif reward.reward_status == 2:
                if reward.reward_type == 1:
                    reward_status_str = '去使用'
                elif reward.reward_type == 2:
                    reward_status_str = '已填写'
                else:
                    reward_status_str = '已领取'
            else:
                reward_status_str = '领取失败'
            lists.append({
                'reward_id': reward.id,
                'reward_type': reward.reward_type,
                'reward_status': reward.reward_status,
                'reward_type_str': reward.get_reward_type_display(),
                'reward_status_str': reward_status_str,
                'reward_name': reward.reward_name,
                'receiver': reward.receiver,
                'address': reward.address,
                'contact_way': reward.contact_way,
                'amount': reward.amount,
                'reward_lists': reward_lists
            })
            data['award_time'] = f'{reward.award_time_begin.strftime("%Y/%m/%d")}~{reward.award_time_end.strftime("%Y/%m/%d")}'
            data['popularity'] = reward.popularity
            data['rank'] = reward.rank
        data['lists'] = lists
        return Response(data, status=status.HTTP_200_OK)

    def retrieve_reward(self, request):
        reward_id = self.request.data.get('reward_id', None)
        receiver = self.request.data.get('receiver', None)
        contact_way = self.request.data.get('contact_way', None)
        province = self.request.data.get('province', None)
        city = self.request.data.get('city', None)
        district = self.request.data.get('district', None)
        place = self.request.data.get('place', None)
        address = self.request.data.get('address', None)
        longitude = self.request.data.get('longitude', None)
        latitude = self.request.data.get('latitude', None)
        login_id = self.request.data.get('login_id', None)
        realname = self.request.data.get('realname', None)
        user = self.request.iser
        if not reward_id:
            return Response({'error': '请上传奖励id'}, status=status.HTTP_400_BAD_REQUEST)
        reward = ScoutTheStoreLeaderboardRewards.objects.filter(id=reward_id, mobile=user.mobile).first()
        if not reward:
            return Response({'error': '无效奖励id'}, status=status.HTTP_400_BAD_REQUEST)
        today = datetime.datetime.now()
        if reward.award_time_begin >= today:
            return Response({'error': '尚未到领奖时间'}, status=status.HTTP_400_BAD_REQUEST)
        if reward.award_time_end <= today:
            return Response({'error': '领奖时间已结束'}, status=status.HTTP_400_BAD_REQUEST)
        if reward.reward_type == 2:
            if reward.reward_status != 1:
                return Response({'error': '奖励已领取'}, status=status.HTTP_400_BAD_REQUEST)
            if not all([receiver, contact_way, address]):
                return Response({'error': '请上传完整收件信息'}, status=status.HTTP_400_BAD_REQUEST)
            try:
                reward.receiver = receiver
                reward.contact_way = contact_way
                # reward.province = province
                # reward.city = city
                # reward.district = district
                # reward.place = place
                reward.address = address
                # reward.longitude = longitude
                # reward.latitude = latitude
                reward.reward_status = 2
                reward.save()
                return Response({'success': '登记信息成功,请等候客户经理联系'}, status=status.HTTP_200_OK)
            except:
                return Response({'error': '补录信息错误'}, status=status.HTTP_400_BAD_REQUEST)
        elif reward.reward_type == 3:
            if reward.reward_status not in [1, 3]:
                return Response({'error': '奖励已领取'}, status=status.HTTP_400_BAD_REQUEST)
            if not login_id:
                return Response({'error': '请上传领取支付宝账号'}, status=status.HTTP_400_BAD_REQUEST)
            if not realname:
                return Response({'error': '请上传领取支付宝账号实名姓名'}, status=status.HTTP_400_BAD_REQUEST)
            reward.reward_status = 4
            reward.login_id = login_id
            reward.realname = realname
            reward.save()
            activity = CashActivity.objects.get(id=937)
            activity_data = reward.cashactivitydata
            if reward.reward_status == 3:
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                activity_data.partner_trade_no = out_biz_no
                activity_data.save()
            else:
                out_biz_no = activity_data.partner_trade_no
            trans_amount = str(activity_data.amount)
            order_title = activity_data.desc
            activity_data.channel_id = activity.ali_channel_id
            alipay_obj = AlipayOpen()
            if activity.ali_channel_id == 8:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88(login_id, realname, out_biz_no, trans_amount, order_title))
            elif activity.ali_channel_id == 11:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88_jizhangben(login_id, realname, out_biz_no, trans_amount, order_title))
            else:
                result = json.loads(alipay_obj.transunitransfer_login_id(login_id, realname, out_biz_no, trans_amount, order_title))
            if result['code'] != '10000':
                activity_data.return_msg = result['sub_msg']
                activity_data.state = 3
                activity_data.received_time = datetime.datetime.now()
                activity_data.merchantuser_id = user.id
                activity_data.mchid = 'alipay'
                activity_data.mobile = user.mobile
                activity_data.channel_id = activity.ali_channel_id
                activity_data.login_id = login_id
                activity_data.realname = realname
                activity_data.save()
                reward.reward_status = 3
                reward.return_msg = result['sub_msg']
                reward.save()
                return Response({'error': '领取失败'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                activity_data.received_time = result['trans_date']
                activity_data.payment_no = result['pay_fund_order_id']
                activity_data.merchantuser_id = user.id
                activity_data.mchid = 'alipay'
                activity_data.state = 2
                activity_data.mobile = user.mobile
                activity_data.login_id = login_id
                activity_data.realname = realname
                activity_data.save()
                reward.reward_status = 2
                reward.save()
                return Response({'success': '领取成功'}, status=status.HTTP_200_OK)
        elif reward.reward_type == 1:
            reward.reward_status = 2
            reward.save()
            return Response({'success': '领取成功'}, status=status.HTTP_200_OK)
        else:
            return Response({'error': '奖项类型有误'}, status=status.HTTP_400_BAD_REQUEST)


class MerchantAuthActivityModelViewSet(ModelViewSet):

    def auth_big_turntable(self, request):
        business_no = self.request.query_params.get('no', None)
        mobile = self.request.query_params.get('mobile', None)
        sign = self.request.query_params.get('sign', None)
        if not business_no:
            return Response({'error': '请上传商户号'}, status=status.HTTP_400_BAD_REQUEST)
        if not mobile:
            return Response({'error': '请上传手机号'}, status=status.HTTP_400_BAD_REQUEST)
        if not sign:
            return Response({'error': '请上传签名'}, status=status.HTTP_400_BAD_REQUEST)
        key = '2DF9C4B73873044ACB70990C2DA134D4'
        body = {}
        body['no'] = business_no
        body['mobile'] = mobile
        check_sign = get_sign(body, key)
        if sign != check_sign:
            return Response({'error': '签名有误'}, status=status.HTTP_400_BAD_REQUEST)
        data_now = datetime.datetime.now()
        check_activity_id_list = MerchantEightEightActivity.objects.filter(activity_start_time__lte=data_now, activity_end_time__gte=data_now, activity_type=4).values_list('id', flat=True)
        if check_activity_id_list:
            activity_status = 3
            white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id__in=check_activity_id_list).order_by('activity_id')
            if white_table:
                white_table = white_table.first()
                white_table.is_visible = 1
                white_table.save()
                activity_id = white_table.activity_id
                check_activity = MerchantEightEightActivity.objects.get(id=activity_id)
                draw_end_time = check_activity.draw_end_time
                available_end_time = check_activity.activity_end_time
                c_time = available_end_time.strftime('%Y-%m-%d %H:%M:%S')
                check_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id__in=check_activity_id_list).count()
                if check_draw:
                    count = 0
                else:
                    count = 1
            else:
                count = 0
                total_count = 0
                activity_id = 85
                check_activity = MerchantEightEightActivity.objects.get(id=85)
                c_time = '%Y-%m-%d %H:%M:%S'
        else:
            count = 0
            total_count = 0
            activity_id = 85
            check_activity = MerchantEightEightActivity.objects.get(id=85)
            c_time = '%Y-%m-%d %H:%M:%S'

        data = {}
        activity_prize_set = MerchantEightEightActivityPrize.objects.filter(activity_id=activity_id)
        lists = []
        for activity_prize in activity_prize_set:
            lists.append({
                'id': activity_prize.id,
                'msg': activity_prize.prize_name,
                'type': activity_prize.prize_type,
                'amount': activity_prize.amount
            })
        data['lists'] = lists
        data['activity_description'] = check_activity.activity_description
        data['description'] = check_activity.activity_description
        data['count'] = count
        data['total_count'] = 1
        data['activity_status'] = 0
        data['c_time'] = c_time
        data['activity_id'] = 5
        return Response(data, status=status.HTTP_200_OK)

    def auth_lucky_draw(self, request):
        business_no = self.request.query_params.get('no', None)
        mobile = self.request.query_params.get('mobile', None)
        sign = self.request.query_params.get('sign', None)
        if not business_no:
            return Response({'error': '请上传商户号'}, status=status.HTTP_400_BAD_REQUEST)
        if not mobile:
            return Response({'error': '请上传手机号'}, status=status.HTTP_400_BAD_REQUEST)
        if not sign:
            return Response({'error': '请上传签名'}, status=status.HTTP_400_BAD_REQUEST)
        key = '2DF9C4B73873044ACB70990C2DA134D4'
        body = {}
        body['no'] = business_no
        body['mobile'] = mobile
        check_sign = get_sign(body, key)
        if sign != check_sign:
            return Response({'error': '签名有误'}, status=status.HTTP_400_BAD_REQUEST)
        data_now = datetime.datetime.now()
        check_activity_id_list = MerchantEightEightActivity.objects.filter(activity_start_time__lte=data_now, activity_end_time__gte=data_now, activity_type=4).values_list('id', flat=True)
        if check_activity_id_list:
            white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id__in=check_activity_id_list)
            if not white_table:
                return Response({'error': '该活动仅限认证商户参加'}, status=status.HTTP_400_BAD_REQUEST)
            activity_id = white_table.first().activity_id
            check_activity = MerchantEightEightActivity.objects.get(id=activity_id)
            draw_end_time = check_activity.draw_end_time
            available_end_time = check_activity.activity_end_time
            available_begin_time = check_activity.activity_start_time
            if available_end_time < data_now:
                return Response({'error': '已过活动抽奖时间,请下期继续参与,多谢支持'}, status=status.HTTP_400_BAD_REQUEST)
            if available_begin_time > data_now:
                return Response({'error': '活动尚未开始领奖时间,敬请期待'}, status=status.HTTP_400_BAD_REQUEST)
            check_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id=activity_id)
            account = f'{data_now.strftime("%Y%m%d")}{business_no}'
            if check_draw:
                return Response({'error': '抽奖次数已消耗完,感谢支持'}, status=status.HTTP_400_BAD_REQUEST)
            draw_list = []
            draw_counts = MerchantEightEightDraw.objects.filter(activity_id=check_activity.id).values('win_type').annotate(Count('win_type'))
            draw_count_dict = {}
            for draw_count in draw_counts:
                draw_count_dict[draw_count['win_type']] = draw_count['win_type__count']
            activity_prize_set = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id).exclude(prize_type=0)
            limit_count = {}
            for activity_prize in activity_prize_set:
                limit_count[activity_prize.id] = activity_prize.count
            for key, value in limit_count.items():
                if key in draw_count_dict:
                    if value > draw_count_dict[key]:
                        draw_list.append(key)
                else:
                    if value > 0:
                        draw_list.append(key)
            if draw_list:
                shuffle(draw_list)
                win_type = draw_list[0]
                activity_prize = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id, id=win_type).first()
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                draw_data = {}
                draw_data['state'] = 1
                draw_data['desc'] = '微邮付商户认证达标回馈'
                draw_data['amount'] = activity_prize.amount
                draw_data['partner_trade_no'] = out_biz_no
                draw_data['win_type'] = win_type
                draw_data['business_no'] = business_no
                draw_data['account'] = account
                draw_data['activity_id'] = activity_id
                draw_data['expired_time'] = draw_end_time
                draw_data['mobile'] = mobile
                instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account)
                data = {}
                data["id"] = win_type
                data["take_id"] = instance.id
                data["amount"] = instance.amount
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = ''
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                data["type"] = activity_prize.prize_type
                if activity_prize.prize_type == 2:
                    data["prize_count"] = activity_prize.prize_count
                else:
                    data["prize_count"] = 1
                merchant = Merchant.objects.filter(wyfMerchantID=business_no).first()
                if merchant:
                    instance.merchantuser_id = merchant.merchantuser_id
                    instance.save()
            else:
                activity_prize = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id, prize_type=0).first()
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                draw_data = {}
                draw_data['state'] = 1
                draw_data['desc'] = '微邮付商户认证达标回馈'
                draw_data['amount'] = 0
                draw_data['partner_trade_no'] = out_biz_no
                draw_data['win_type'] = 6
                draw_data['business_no'] = business_no
                draw_data['account'] = account
                draw_data['activity_id'] = activity_id
                draw_data['expired_time'] = draw_end_time
                draw_data['mobile'] = mobile
                instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account)
                data = {}
                data["id"] = activity_prize.id
                data["take_id"] = instance.id
                data["amount"] = instance.amount
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = ''
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                data["type"] = activity_prize.prize_type
                data["prize_count"] = 1
            try:
                check_activity.total_count += 1
                check_activity.save()
            except:
                pass
            return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
        else:
            if data_now >= datetime.datetime.strptime("2025-07-31 23:59:59", "%Y-%m-%d %H:%M:%S"):
                return Response({'error': '活动已结束,感谢支持邮政活动'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                return Response({'error': '活动尚未开始,敬请期待'}, status=status.HTTP_400_BAD_REQUEST)

    def auth_lucky_draw_list(self, request):
        business_no = self.request.query_params.get('no', None)
        mobile = self.request.query_params.get('mobile', None)
        sign = self.request.query_params.get('sign', None)
        if not business_no:
            return Response({'error': '请上传商户号'}, status=status.HTTP_400_BAD_REQUEST)
        if not mobile:
            return Response({'error': '请上传手机号'}, status=status.HTTP_400_BAD_REQUEST)
        if not sign:
            return Response({'error': '请上传签名'}, status=status.HTTP_400_BAD_REQUEST)
        key = '2DF9C4B73873044ACB70990C2DA134D4'
        body = {}
        body['no'] = business_no
        body['mobile'] = mobile
        check_sign = get_sign(body, key)
        if sign != check_sign:
            return Response({'error': '签名有误'}, status=status.HTTP_400_BAD_REQUEST)
        today = datetime.datetime.now()
        activity_id_lsit = MerchantEightEightActivity.objects.filter(activity_start_time__lte=today, activity_end_time__gte=today, activity_type=4).values_list('id', flat=True)
        queryset = MerchantEightEightDraw.objects.filter(business_no=business_no, expired_time__gte=today, activity_id__in=activity_id_lsit).exclude(win_type=6)
        if queryset:
            data = MerchantEightEightDrawListModelSerializer(queryset, many=True).data
            return Response(data, status=status.HTTP_200_OK)
        else:
            return Response([], status=status.HTTP_200_OK)

    def receive_auth_lucky_draw(self, request):
        business_no = self.request.query_params.get('no', None)
        mobile = self.request.query_params.get('mobile', None)
        sign = self.request.query_params.get('sign', None)
        login_id = self.request.query_params.get('login_id', None)
        realname = self.request.query_params.get('realname', None)
        draw_id = self.request.query_params.get('draw_id', None)
        if not business_no:
            return Response({'error': '请上传商户号'}, status=status.HTTP_400_BAD_REQUEST)
        if not mobile:
            return Response({'error': '请上传手机号'}, status=status.HTTP_400_BAD_REQUEST)
        if not sign:
            return Response({'error': '请上传签名'}, status=status.HTTP_400_BAD_REQUEST)
        if not login_id:
            return Response({'error': '请上传领取支付宝账号'}, status=status.HTTP_400_BAD_REQUEST)
        if not realname:
            return Response({'error': '请上传领取支付宝账号实名姓名'}, status=status.HTTP_400_BAD_REQUEST)
        key = '2DF9C4B73873044ACB70990C2DA134D4'
        body = {}
        body['no'] = business_no
        body['mobile'] = mobile
        check_sign = get_sign(body, key)
        if sign != check_sign:
            return Response({'error': '签名有误'}, status=status.HTTP_400_BAD_REQUEST)
        today = datetime.datetime.now()
        activity_id_lsit = MerchantEightEightActivity.objects.filter(activity_start_time__lte=today, activity_end_time__gte=today, activity_type=4).values_list('id', flat=True)
        queryset = MerchantEightEightDraw.objects.filter(business_no=business_no, expired_time__gte=today, activity_id__in=activity_id_lsit).exclude(win_type=6)
        try:
            instance = queryset.get(id=draw_id)
        except:
            return Response({'error': '无效奖品id'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.state not in [1, 3]:
            return Response({'error': '奖励状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.state == 3:
            out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            instance.partner_trade_no = out_biz_no
            instance.save()
        instance.state = 5
        instance.login_id = login_id
        instance.realname = realname
        instance.channel_id = 11
        instance.save()
        alipay_obj = C_AlipayOpen()
        trans_amount = str(instance.amount)
        order_title = instance.desc
        out_biz_no = instance.partner_trade_no
        identity = login_id
        result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88_jizhangben(identity, realname, out_biz_no, trans_amount, order_title))
        if result['code'] != '10000':
            instance.return_msg = result['sub_msg']
            instance.state = 3
            instance.received_time = datetime.datetime.now()
            instance.save()
            return Response({'error': f'领取失败{result["sub_msg"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        else:
            instance.received_time = result['trans_date']
            instance.payment_no = result['pay_fund_order_id']
            instance.state = 2
            instance.save()
            try:
                check_activity = MerchantEightEightActivity.objects.get(activity_id=instance.activity_id)
                check_activity.total_amount += instance.amount
                check_activity.save()
            except:
                pass
            return Response({'success': '领取成功'}, status=status.HTTP_200_OK)















